package com.dcd.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import sun.misc.BASE64Encoder;
import java.net.URLEncoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ExcelFileUtils {
    /**
     * 下载文件时，针对不同浏览器，进行附件名的编码
     *
     * @param filename
     *            下载文件名
     * @param agent
     *            客户端浏览器
     * @return 编码后的下载附件名
     * @throws IOException
     */
    public static String encodeDownloadFilename(String filename, String agent)
            throws IOException {
        if (agent.contains("GoogleChrome")) { // 谷歌浏览器
            filename = "=?UTF-8?B?"
                    + new BASE64Encoder().encode(filename.getBytes("utf-8"))
                    + "?=";
            filename = filename.replaceAll("\r\n", "");
        } else { // IE及其他浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+"," ");
        }
        return filename;
    }

    public static void excelExport(HttpServletResponse response, HttpServletRequest request, HSSFWorkbook hssfWorkbook, String filename){

        // 通过浏览器下载导出
        // 设置表头信息
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel,charset=utf-8");
            String agent = request.getHeader("user-agent");
            filename = encodeDownloadFilename(filename, agent);
            response.setHeader("Content-Disposition", new String(("attachment;filename=" + filename).getBytes(), "iso-8859-1"));
            hssfWorkbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 关闭
            try {
                hssfWorkbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
